package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.exception.BusinessException;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.domain.UserLike;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.Friends;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class UserInfoSerivce {
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private UserLikeApi userLikeApi;
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        log.info("将图片{}上传到阿里云oss",headPhoto.getName());
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        log.info("百度云判断{}包含人脸",detect?"":"不");
        //2.1 如果不包含人脸，抛出异常
        if(!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性

        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    @Async
    public List<UserInfo> friends(int code,Long userId) {
        if (code == Constants.LIKE_MUTUAL|| code == Constants.LIKE_ME||code == Constants.LIKE_YOU){
            List<UserLike> userLikes = userLikeApi.getFriend(code,userId);
            log.info("userLikes == {}",userLikes);
            List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
            if (likeUserIds.size() <= 0){
                return null;
            }
            Map<Long, UserInfo> map = userInfoApi.findByIds(likeUserIds,null);
            ArrayList<UserInfo> list = new ArrayList<>();
            for (Long likeUserId : likeUserIds) {
                Friends friends = new Friends();
                RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(friends.getId());
                BeanUtils.copyProperties(likeUserId,friends);
                friends.setMatchRate(recommendUser == null?99:recommendUser.getScore().intValue());
                friends.setAlreadLove(true);
                log.info("friends ==== {}",friends);
                log.info("friends.id ==== {}",friends.getId());
                list.add(map.get(likeUserId));
            }
            return list;
        }
        return null;
    }

    public List<UserInfo> getFriend(int code,Long userId) {
        switch (code){
            case Constants.LIKE_MUTUAL: //互相喜欢

                break;
            case Constants.LIKE_ME: //我喜欢的
                Set<String> LikeMeId = redisTemplate.opsForSet().members(Constants.USER_LIKE_KEY + UserHolder.getUserId());
                break;
            case Constants.LIKE_YOU: //喜欢我的
                //redisTemplate.opsForSet()
                break;
            default:
                break;
        }
        return null;
    }
}
